package com.sen.uaa.config;

import com.sen.common.auth.token.CaAuthenticationToken;
import com.sen.uaa.service.UserServiceImpl;
import lombok.Setter;
import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.authentication.InternalAuthenticationServiceException;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.userdetails.UserDetails;

/**
 * @author esjiang
 */
@Setter
public class CaAuthenticationProvider implements AuthenticationProvider {
    private UserServiceImpl userDetailsService;

    @Override
    public Authentication authenticate(Authentication authentication) {
        CaAuthenticationToken authenticationToken = (CaAuthenticationToken) authentication;
        String keyNum = (String) authenticationToken.getPrincipal();
        UserDetails user = userDetailsService.loadUserByKeyNum(keyNum);
        if (user == null) {
            throw new InternalAuthenticationServiceException("ca序列号不正确");
        }
        CaAuthenticationToken authenticationResult = new CaAuthenticationToken(user, user.getAuthorities());
        authenticationResult.setDetails(authenticationToken.getDetails());
        return authenticationResult;
    }

    @Override
    public boolean supports(Class<?> authentication) {
        return CaAuthenticationToken.class.isAssignableFrom(authentication);
    }
}
